<template>
  <div class="login-phone">
    <el-form label-width="70px" :model="phone" :rules="rules" ref="formRef">
      <el-form-item label="手机号" prop="cellphone">
        <el-input
          v-model="phone.cellphone"
          placeholder="请输入手机号"
        ></el-input>
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <div class="verification">
          <el-input v-model="phone.code" placeholder="请输入验证码"></el-input>
          <el-button
            type="primary"
            :disabled="timeFlag"
            class="get-btn"
            @click="handleGetCode"
            >{{ timeFlag ? `重新获取(${waitTime})` : '获取验证码' }}</el-button
          >
        </div>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref } from 'vue'
import { useStore } from 'vuex'
import { rules } from '../config/phone-config'
import { ElForm } from 'element-plus'
import { phoneSentCode, phoneVerifyCode } from '@/service/login'
import LocalCache from '@/utils/cache'
import { Message } from '@/utils/message'
export default defineComponent({
  emits: ['closeDialog'],
  setup(props, { emit }) {
    const phone = reactive({
      cellphone: LocalCache.getCache('cellphone') ?? null,
      code: null
    })
    const store = useStore()

    const formRef = ref<InstanceType<typeof ElForm>>()
    const clickLogin = () => {
      formRef.value?.validate((vali) => {
        if (vali) {
          verifyCode(phone.cellphone, phone.code)
        } else {
          Message('验证失败', 'warning')
        }
      })
    }
    const verifyCode = (phoneNum: number | null, captcha: number | null) => {
      phoneVerifyCode(phoneNum, captcha).then((res: any) => {
        if (res.code == 200 && res.data) {
          store.dispatch('login/phoneLoginAction', { ...phone })
          emit('closeDialog')
        } else {
          Message(res.message, 'warning')
        }
      })
    }

    const init = () => {
      phone.cellphone = null
      phone.code = null
    }

    const handleGetCode = () => {
      waitTimeFn(waitTime)
      phoneSentCode(phone.cellphone).then((res: any) => {
        if (res.code != 200) {
          clearInterval(timeId)
        }
      })
    }
    const timeFlag = ref(false)
    const waitTime = ref(60)
    let timeId = 0
    function waitTimeFn(obj: any) {
      timeFlag.value = true
      const start = obj.value
      timeId = setInterval(() => {
        obj.value--
        if (obj.value == 0) {
          clearInterval(timeId)
          obj.value = start
          timeFlag.value = false
        }
      }, 1000)
    }

    return {
      phone,
      rules,
      clickLogin,
      formRef,
      init,
      handleGetCode,
      waitTime,
      timeFlag
    }
  }
})
</script>

<style scoped lang="less">
.login-phone {
  padding-top: 20px;
  .verification {
    display: flex;

    .get-btn {
      margin-left: 8px;
    }
  }
}
</style>
